//
//  BHCompetitionViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/10.
//

import UIKit

class BHCompetitionViewController: BHBaseViewController {

    lazy var filterHeaderView: BHCompetitionFilterView = {
        let view = BHCompetitionFilterView.loadFromXib()
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: BHCompetitionFilterView.headerHeight)
        view.delegate = self
        return view
    }()
    
    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout.init()
        layout.sectionInset = .zero
        let view = UICollectionView.buildCollectionView(layout: layout)
        view.frame = CGRect(x: 0, y: UIScreen.begainY+BHCompetitionFilterView.headerHeight, width: UIScreen.width, height: UIScreen.showHeight-BHCompetitionFilterView.headerHeight)
        view.register(UINib.init(nibName: "BHWonderfulGameCell", bundle: nil), forCellWithReuseIdentifier: "BHWonderfulGameCell")
        view.register(BHGameBannerCell.self, forCellWithReuseIdentifier: "BHGameBannerCell")
        view.backgroundColor = .white
        view.delegate = self
        view.dataSource = self
        
        return view
    }()
    
    lazy var classFilterView: BHCompetitionDoubleView = {
        let view = BHCompetitionDoubleView.init(type: 0)
        view.frame = CGRect(x: 0, y: UIScreen.begainY+BHCompetitionFilterView.headerHeight, width: UIScreen.width, height: UIScreen.height-BHCompetitionFilterView.headerHeight-UIScreen.begainY)
        view.delegate = self
        return view
    }()
    
    lazy var areaFilterView: BHCompetitionAreaChoseView = {
        let view = BHCompetitionAreaChoseView.init(frame: CGRect(x: 0, y: UIScreen.begainY+BHCompetitionFilterView.headerHeight, width: UIScreen.width, height: UIScreen.height-BHCompetitionFilterView.headerHeight-UIScreen.begainY))
        view.delegate = self
        return view
    }()
    
    lazy var sortFilterView: BHCompetitionSortView = {
        let view = BHCompetitionSortView.init(frame: CGRect(x: 0, y: UIScreen.begainY+BHCompetitionFilterView.headerHeight, width: UIScreen.width, height: UIScreen.height-BHCompetitionFilterView.headerHeight-UIScreen.begainY))
        view.type = 0
        view.delegate = self
        view.itemArray = BHHomeCityModel.gameSortArray
        return view
    }()
    
//    lazy var stateFilterView: BHCompetitionSortView = {
//        let view = BHCompetitionSortView.init(frame: CGRect(x: 0, y: UIScreen.begainY+BHCompetitionFilterView.headerHeight, width: UIScreen.width, height: UIScreen.height-BHCompetitionFilterView.headerHeight-UIScreen.begainY))
//        view.type = 1
//        return view
//    }()
    
    lazy var bannerCell: BHGameBannerCell = { [unowned self] in
        let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "BHGameBannerCell", for: IndexPath.init(row: 0, section: 0)) as! BHGameBannerCell
        return cell
        
    }()
    
    fileprivate var searchKey: String = ""
    fileprivate var sort: String = ""
    fileprivate var typeModel: BHCommonSortTypeModel = BHCommonSortTypeModel.init()

    fileprivate var gameArray: [BHCommonGameModel] = []
    fileprivate var bannerArray: [BHCommonBannerModel] = []
    
    fileprivate var provinceName: String = ""
    fileprivate var cityName: String = ""
    fileprivate var areaName: String = ""


    override func viewDidLoad() {
        super.viewDidLoad()

        self.bh_navigationBar.title_label.text = "热门赛事"
        self.view.addSubview(self.collectionView)
        self.view.addSubview(self.filterHeaderView)
        
        self.view.addSubview(self.classFilterView)
        self.view.addSubview(self.areaFilterView)
        self.view.addSubview(self.sortFilterView)
//        self.view.addSubview(self.stateFilterView)
        
        self.queryBannerService()
        self.loadGameService()
        self.queryFilterTypeService(model: nil)
        self.queryProvince()
        
        self.collectionView.addRefresh { [weak self] in
            self?.page = 1
            self?.loadGameService()
        }
        
        self.collectionView.addloadMore { [weak self] in
            self?.page += 1
            self?.loadGameService()
        }
    }
    
}

// 切换筛选条件的点击
extension BHCompetitionViewController: BHCompetitionFilterViewDelegate {
    func fitterHeaderBegainSearch() {
        self.classFilterView.showOrHide(show: false)
        self.areaFilterView.showOrHide(show: false)
        self.sortFilterView.showOrHide(show: false)
        
        self.filterHeaderView.resetAllState()
    }
    
    func filterHeaderSearchForKey(key: String) {
        self.searchKey = key
        self.collectionView.mj_header?.beginRefreshing()
    }
    
    func filterHeaderDidChose(sender: UIButton) {
        let index = sender.tag-100
        self.classFilterView.showOrHide(show: index == 0)
        self.areaFilterView.showOrHide(show: index == 1)
        self.sortFilterView.showOrHide(show: index == 2)
//        self.stateFilterView.showOrHide(show: index == 3)
    }
}

extension BHCompetitionViewController: BHCompetitionDoubleViewDelegate {
    func didChoseLeft(model: BHCommonSortTypeModel) {
        self.queryFilterTypeService(model: model)
    }
    
    func didChoseRight(model: BHCommonSortTypeModel) {
        self.typeModel.parentId = model.parentId
        self.typeModel.typeId = model.typeId
       
        self.filterHeaderView.changeIndexBtnText(index: 0, text: "\(model.text) ")
        self.collectionView.mj_header?.beginRefreshing()
    }
    
    func didTypeChoseClose() {
        self.classFilterView.showOrHide(show: false)
        self.filterHeaderView.resetAllState()
    }
    
}


extension BHCompetitionViewController: BHCompetitionAreaChoseViewDelegate {
    func didChoseProvince(model: BHHomeCityModel) {
        if model.childArray.count == 0 {
            self.queryCity(provinceModel: model)
        }else {
            self.provinceName = model.name
        }
    }
    
    func didChoseCity(model: BHHomeCityModel) {
        if model.childArray.count == 0 {
            self.queryArea(cityModel: model)
        }else {
            self.cityName = model.name
        }
    }
    
    func didChoseArea(areaModel: BHHomeCityModel) {
        self.areaName = areaModel.name
        
        self.filterHeaderView.changeIndexBtnText(index: 1, text: "\(areaModel.name) ")
        self.collectionView.mj_header?.beginRefreshing()
    }
    
    func didPlaceChoseClose() {
        self.areaFilterView.showOrHide(show: false)
        
        self.filterHeaderView.resetAllState()
    }
}
extension BHCompetitionViewController: BHCompetitionSortViewDelegate {
    func didSortChoseIndex(model: BHHomeCityModel?, index: Int, view: BHCompetitionSortView) {
        self.filterHeaderView.changeIndexBtnText(index: 2, text: "\(model?.name ?? "排序") ")
        if model != nil {
            self.sort = model?.code ?? ""
            self.collectionView.mj_header?.beginRefreshing()
        }
    }
    
    func didSortViewClose() {
        self.sortFilterView.showOrHide(show: false)
        self.filterHeaderView.resetAllState()
    }
    
}

extension BHCompetitionViewController: UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0 {
            if self.bannerArray.count == 0 {
                return 0
            }
            return 1
        }
        return self.gameArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if indexPath.section == 0 {
            if self.bannerArray.count == 0 {
                return .zero
            }
            return CGSize(width: UIScreen.width, height: BHGameBannerCell.cellHeight)
        }
        return CGSize(width: UIScreen.width, height: BHWonderfulGameCell.gameHeight)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.section == 1 {
            let model = self.gameArray[indexPath.row]
            BHRouter.shared.bh_goGameDetail(gameId: model.gameId)
  
        }
    }
}

extension BHCompetitionViewController: UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.section == 0 {
            return self.bannerCell
        }else {
            let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "BHWonderfulGameCell", for: indexPath) as! BHWonderfulGameCell
            let model = self.gameArray[indexPath.row]
            cell.model = model
            return cell
        }
    }
    
}

extension BHCompetitionViewController {
    
    func loadGameService()  {
        let dic = self.appendDic()
        let manager = BHHTTPClient.init()
        manager.get(url: String.game_filter_list_url, paramters: dic) { (success, errorMsg, responseDic) in
            self.collectionView.endRefresh()
            self.collectionView.endLoading()
            
            if success == true {
                let result = BHJsonTool.decodeDicFromDic(dic: responseDic, key: "result")
                let total = BHJsonTool.decodeIntFromDic(dic: result, key: "total")

                if self.page == 1 {
                    self.collectionView.endLoadWithNoMoreData(false)
                    if self.gameArray.count != 0 {
                        self.gameArray.removeAll()
                    }
                }
                
                let record = BHJsonTool.decodeArrayFromDic(dic: result, key: "records")
                for dic in record {
                    let model = BHCommonGameModel.init()
                    model.parseDic(dic as! [String : Any])
                    self.gameArray.append(model)
                }
                self.collectionView.reloadData()
                if self.gameArray.count >= total {
                    self.collectionView.endLoadWithNoMoreData(true)
                }
                    
            }else {
                BHToast.toast(text: errorMsg) 
            }
        }
        
    }
    
    func appendDic() -> [String:Any] {
        var dic: [String:Any] = [:]
        dic["pageNo"] = self.page
        dic["pageSize"] = 20
        dic["typeOneValue"] = self.typeModel.parentId
        dic["typeTwoValue"] = self.typeModel.typeId
        dic["provinceName"] = self.provinceName
        dic["cityName"] = self.cityName
        dic["regionName"] = self.areaName
        dic["search"] = self.searchKey
        dic["sort"] = self.sort
        dic["longitude"] = BHLocationManager.shared.longitude
        dic["latitude"] = BHLocationManager.shared.latitude
        
        return dic
    }
    
    func queryBannerService() {
        BHCommonService.queryBannerService(type: 3) {[weak self] (array) in
            self?.bannerArray = array
            self?.bannerCell.banner = array
            self?.collectionView.reloadData()
        }
    }
}

// 查询筛选的分类
extension BHCompetitionViewController {
    func queryFilterTypeService(model: BHCommonSortTypeModel?)  {
        if model == nil {
            BHCommonService.queryTypeOneService(type: 2) { (modelArray) in
                self.classFilterView.leftArray = modelArray
            }
        }else {
            BHCommonService.queryTypeTwoService(parentModel: model!) { (array) in
                model?.childArray = array
                self.classFilterView.rightTable.reloadData()
            }
        }
    }
}

// 查询筛选的省市区
extension BHCompetitionViewController {
    func queryProvince()  {
        BHCommonService.queryProvinceService(appendAll: true) { (provinceArray) in
            self.areaFilterView.itemArray = provinceArray
        }
    }
    
    func queryCity(provinceModel: BHHomeCityModel)  {
        BHCommonService.queryCityService(provinceModel: provinceModel, appendAll: true,handler: { (model) in
            self.areaFilterView.provinceTab.reloadData()
            self.areaFilterView.cityTab.reloadData()
        })
    }
    
    func queryArea(cityModel: BHHomeCityModel)  {
        BHCommonService.queryAreaService(cityModel: cityModel, appendAll: true,handler: { (model) in
            self.areaFilterView.cityTab.reloadData()
            self.areaFilterView.areaTab.reloadData()
        })
    }
}
